package com.fileCenter.dao.impl;

import java.util.Collections;
import java.util.List;

import com.fileCenter.dao.BaseDAO;
import com.fileCenter.dao.ReviewDAO;
import com.fileCenter.exception.FileCenterException;
import com.fileCenter.pojo.Review;

@SuppressWarnings("unchecked")
public class ReviewDAOImpl extends BaseDAO implements ReviewDAO {

	private static String queryAllHQL = "from Review";
	private static String queryByRecUserIdAndFileIdHQL = "from Review where recModelId=:recModelId and fileId=:fileId";
	private static String queryByRecUserIdHQL = "from Review where recModelId=:recModelId";
	
	@Override
	public void save(Review review) throws FileCenterException {
		if (review == null) {
			throw new FileCenterException("param error!");
		}
		getHibernateTemplate().saveOrUpdate(review);
	}

	@Override
	public List<Review> queryAll() throws FileCenterException {
		return getHibernateTemplate().find(queryAllHQL);
	}

	@Override
	public List<Review> queryByRecUserIdAndFileId(long recUserId, long fileId) {
		if (recUserId <= 0 || fileId <= 0) {
			return Collections.emptyList();
		}
		return getHibernateTemplate().findByNamedParam(queryByRecUserIdAndFileIdHQL, 
				new String[]{"recModelId", "fileId"}, new Object[]{recUserId, fileId});
	}

	@Override
	public List<Review> queryByRecUserId(long recUserId) {
		if (recUserId <= 0) {
			return Collections.emptyList();
		}
		return getHibernateTemplate().findByNamedParam(queryByRecUserIdHQL, 
				"recModelId", recUserId);		
	}

	@Override
	public Review queryById(long reviewId) {
		if (reviewId <= 0) {
			return null;
		}
		return (Review) getHibernateTemplate().get(Review.class, reviewId);
	}

	@Override
	public void update(Review review) {
		if (review == null || review.getId() <= 0) {
			throw new FileCenterException("param error!");
		}
		getHibernateTemplate().update(review);
	}
}
